# -*- coding: UTF-8 -*-
# server_assets
# @File : fight.py
# @Date : 2023-08-30
# @Author  : wuzhouhai
# @Desc:
import KBEngine
from KBEDebug import *

import random
import math
import operator
from module.BattleStateMachine import BattleStateMachine
import s_skillProperty
import s_skillTarget
import s_skillEffect
import s_skillBuff
import s_partyInfo

import ConstantDefine
from MsgDatas import MsgFightResult


# 伤害计算公式
def DamageFormula(actor, enemy, isCri, effectInfo):
    """伤害计算"""
    defenseMin = {1: enemy['physicalDefense'], 2: enemy['magicDefense'],
                  3: enemy['magicDefense'],
                  4: enemy['physicalDefense'],
                  5: enemy['magicDefense'],
                  6: enemy['magicDefense']}.get(actor['chaProfessionType'], 0)  # 获取防御下限

    defenseMax = {1: enemy['physicalDefenseMax'], 2: enemy['magicDefenseMax'],
                  3: enemy['magicDefenseMax'],
                  4: enemy['physicalDefenseMax'],
                  5: enemy['magicDefenseMax'],
                  6: enemy['magicDefenseMax']}.get(actor['chaProfessionType'], 0)  # 获取防御上限

    attackBaseMin = {1: actor['physicalAttack'], 2: actor['scAttack'],
                     3: actor['magicAttack'],
                     4: actor['physicalAttack'],
                     5: actor['magicAttack'],
                     6: actor['scAttack']}.get(actor['chaProfessionType'], 0)  # 获取攻击下限

    attackBaseMax = {1: actor['physicalAttackMax'], 2: actor['scAttackMax'],
                     3: actor['magicAttackMax'],
                     4: actor['physicalAttackMax'],
                     5: actor['magicAttackMax'],
                     6: actor['scAttackMax']}.get(actor['chaProfessionType'], 0)  # 获取攻击上限

    godDefAdd = {1: enemy['physicalDefGodAdd'], 2: enemy['magicDefGodAdd'],
                 3: enemy['magicDefGodAdd'],
                 4: enemy['physicalDefGodAdd'],
                 5: enemy['magicDefGodAdd'],
                 6: enemy['magicDefGodAdd']}.get(actor['chaProfessionType'], 0)  # 获取防御下限

    luckAtk = actor['luckAtk']  # 攻击幸运值
    luckDef = actor['luckDef']  # 诅咒值
    # [（物理攻击力上限+物理攻击力下限）+（物理攻击力上限-物理攻击力下限）*（幸运-诅咒）*4/400]/2*randbetween(80+（幸运-诅咒）*4,120)/100
    atkHurt = int(((attackBaseMax + attackBaseMin) * (actor['hurtGodAdd'] * 0.01 + 1) + float(
        (attackBaseMax - attackBaseMin) * (luckAtk - luckDef) * 4) / 400) * (
                      random.randint(80 + (luckAtk - luckDef) * 4, 120)) * 0.01)
    # 物理防御力上限+物理防御力下限*（1-诅咒/100）
    atkdef = int(((defenseMax + defenseMin) * 0.5 * (1 + godDefAdd * 0.01)) * (1 - luckDef * 0.01))  # *0.3
    # log.msg("enemy:%s,atkHurt:%s,atkdef:%s"%(enemy['chaId'],atkHurt,atkdef))
    if isCri == 1:
        # 暴击基础伤害
        atkHurt = int((atkHurt - atkdef) * (120 + actor['criHarm'] + actor['criHurtGodAdd']) * 0.01)
    else:
        # 基础伤害
        atkHurt -= atkdef
    hurt = 0
    # 计算技能一段伤害
    if effectInfo.get('hurtValueType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_VALUE_TYPE_NORMAL:
        hurt += atkHurt
    elif effectInfo.get('hurtValueType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_VALUE_TYPE_ATKPERCENT:
        hurt += int(round(atkHurt * effectInfo.get('hurtValue', 0) * 0.01))
    elif effectInfo.get('hurtValueType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_VALUE_TYPE_FIXED:
        hurt += effectInfo.get('hurtValue', 0)
    elif effectInfo.get('hurtValueType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_VALUE_TYPE_HP_PERCENT:
        hurt += int(round(enemy['chaMaxHp'] * effectInfo.get('hurtValue', 0) * 0.01))
    elif effectInfo.get('hurtValueType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_VALUE_TYPE_HP_PERCENT_N:
        hurt += int(round(enemy['chaCurrentHp'] * effectInfo.get('hurtValue', 0) * 0.01))

    # 计算技能真实伤害
    if effectInfo.get('realHurtValueType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_VALUE_TYPE_ATKPERCENT:
        hurt += int(round(atkHurt * effectInfo.get('realHurtValue', 0) * 0.01))
    elif effectInfo.get('realHurtValueType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_VALUE_TYPE_FIXED:
        hurt += effectInfo.get('realHurtValue', 0)
    elif effectInfo.get('realHurtValueType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_VALUE_TYPE_HP_PERCENT:
        hurt += int(round(enemy['chaMaxHp'] * effectInfo.get('realHurtValue', 0) * 0.01))
    elif effectInfo.get('realHurtValueType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_VALUE_TYPE_HP_PERCENT_N:
        hurt += int(round(enemy['chaCurrentHp'] * effectInfo.get('realHurtValue', 0) * 0.01))

    # 计算其他附加伤害
    # 强魂附加伤害
    hurt += int(round(hurt * actor['qiangHunHurtPercent'] * 0.01))
    # 判断无法破防情况
    if hurt <= 0:
        hurt = 1

    return hurt


def MpProduce(enemy, effectInfo):
    """计算怒气"""
    if effectInfo.get('effectValueType', 0) == 0:
        return 0
    elif effectInfo.get('effectValueType', 0) == ConstantDefine.DEFINE_EFFECT_VALUE_TYPE_PERCENT:
        return int(round(enemy['chaMaxMp'] * effectInfo.get('effectValue', 0) * 0.01))
    elif effectInfo.get('effectValueType', 0) == ConstantDefine.DEFINE_EFFECT_VALUE_TYPE_FIXED_VALUE:
        return effectInfo.get('effectValue', 0)
    elif effectInfo.get('effectValueType', 0) == ConstantDefine.DEFINE_EFFECT_VALUE_TYPE_PERCENT:
        return int(round(enemy['chaCurrentMp'] * effectInfo.get('effectValue', 0) * 0.01))


def HpProduce(enemy, effectInfo, actor=None):
    """计算治疗"""
    if effectInfo.get('effectValueType', 0) == 0:
        return 0
    elif effectInfo.get('effectValueType', 0) == ConstantDefine.DEFINE_EFFECT_VALUE_TYPE_PERCENT:
        return int(round(enemy['chaMaxHp'] * effectInfo.get('effectValue', 0) * 0.01))
    elif effectInfo.get('effectValueType', 0) == ConstantDefine.DEFINE_EFFECT_VALUE_TYPE_FIXED_VALUE:
        return effectInfo.get('effectValue', 0)
    elif effectInfo.get('effectValueType', 0) == ConstantDefine.DEFINE_EFFECT_VALUE_TYPE_PERCENT:
        return int(round(enemy['chaCurrentHp'] * effectInfo.get('effectValue', 0) * 0.01))
    elif effectInfo.get('effectValueType', 0) == ConstantDefine.DEFINE_EFFECT_VALUE_TYPE_PERCENT_ACK:
        if actor:
            attackBaseMin = {1: actor['physicalAttack'], 2: actor['scAttack'],
                             3: actor['magicAttack'],
                             4: actor['physicalAttack'],
                             5: actor['magicAttack'],
                             6: actor['scAttack']}.get(actor['chaProfessionType'], 0)  # 获取攻击下限
            return int(round(attackBaseMin * effectInfo.get('effectValue', 0) * 0.01))


def CalculateSkillDadog(enemy, effectInfo):
    """计算技能闪避"""
    if effectInfo.get('effectType', 0) == ConstantDefine.DEFINE_EFFECT_TYPE_PRODUCE_SP or \
            effectInfo.get('effectType', 0) == ConstantDefine.DEFINE_EFFECT_TYPE_TREAT:
        return False
    # dodgeRate = (enemy['dodgeRate'])/(695.4*math.exp(0.03788*enemy['chaLevel']))
    dodgeRate = (0.08 * enemy['dodgeRate']) / (
            0.36 * math.pow(enemy['chaLevel'], 2) - (16.7 * enemy['chaLevel']) + 300.0)
    hitRate = 10000 - int(dodgeRate * 10000)
    if hitRate < 5000:
        hitRate = 5000
    rate = random.randint(1, 10000)
    # 判断是否命中，命中时的操作
    if rate <= hitRate:
        return False
    return True


def CalculateSkillCri(actor, effectInfo):
    """判断暴击"""
    if effectInfo.get('effectType', 0) == ConstantDefine.DEFINE_EFFECT_TYPE_PRODUCE_SP or \
            effectInfo.get('effectType', 0) == ConstantDefine.DEFINE_EFFECT_TYPE_REODUCE_SP:
        return False
    rate = random.randint(1, 10000)
    # critRate = int(((actor['critRate'])/(695.4*math.exp(0.03788*actor['chaLevel'])))*10000)
    critRate = int((0.16 * actor['critRate']) / (
            0.36 * math.pow(actor['chaLevel'], 2) - (16.7 * actor['chaLevel']) + 300.0) * 10000)
    # print u'随机值:%d,暴击值:%d,角色暴击值:%d'%(rate,critRate,actor['critRate'])
    if rate < critRate:
        return True
    return False


class Fight:
    """战斗类"""

    MAX_ROUND = 20  # 战斗的最大回合数

    def __init__(self, activeSide, passiveSide, partyId, guanQiaId, isAthletics=False, isWorldBoss=False):
        """初始化战斗类
        @param activeSide: 攻击方
        @param passiveSide: 防守方
        """
        # self.activeSide = activeSide  # 主动方方阵对象
        self.isAthletics = isAthletics  # 是否为竞技战斗
        # self.passiveSide = passiveSide  # 被动方方阵对象
        self.activeSideMembers = activeSide.getMembers()  # 字典
        self.passiveSideMembers = passiveSide.getMembers()  # 字典
        self.fighters = {}  # 所有战斗成员数据{chaBattleId:fightdata}
        # self.orderList = []  # 攻速排序列表
        self.activeList = []  # 主动方的成员的战场id列表
        self.passiveList = []  # 被动方得成员的战场id列表
        self.activeSideOrder = [2, 3, 1, 4, 5, 6]  # 进攻方出手顺序
        self.passiveSideOrder = [1, 2, 3, 4, 5, 6]  # 防守方出手顺序
        self.now_round = 0  # 战斗的当前回合数
        self.FightData = []  # 战斗产生的数据
        self.fightOrder = []  # 战斗序列
        self.worldBoss = None  # 世界BOSSID
        self.worldBossReMindHp = 0  # 世界BOSS剩余血量
        self.worldBossHp = 0  # 世界BOSS战斗开始血量
        self.isWorldBossFight = isWorldBoss
        self.battleStateMachine = BattleStateMachine(self)  # 战斗的状态机
        self.partyExpAddPercent = 0  # 经验加成百分比
        self.initBattlefield()  # 初始化战场
        self.battleResult = 1  # 战斗结果
        self.hasboss = False  # 战斗中是否有boss
        self.partyId = partyId  # 怪物组ID
        self.partyExp = 0  # 获得经验
        self.partyMoney = 0  # 获得金钱
        self.fightTowerCoin = 0  # 获得塔币
        self.fightTowerGold = 0  # 获得元宝
        self.partySkillPoints = 0  # 获得技能点
        self.athleticPoint = 0  # 获得竞技点
        self.ordAtkCount = 2  # 普通攻击次数
        self.lootGroupId = 0  # 掉落组ID
        self.lootNumber = 1  # 掉落数目
        self.lootList = []  # 掉落列表
        self.lootSellList = []  # 掉落出售列表
        self.lootGetList = []  # 掉落获取列表
        self._msgFightResult = MsgFightResult.MsgFightResult()  # 战斗结果对象
        if self.isAthletics:
            self.initAthleticAward()
        elif self.isWorldBossFight:
            pass
        else:
            self.initGuanQiaAward()

        self.guanQia = guanQiaId
        self.skillProficiencyList = []  # 技能熟练度增长列表
        self.formatInitFightData()

    def initAthleticAward(self):
        """初始化竞技奖励"""
        self.partyMoney = 0  # 获得金钱
        self.athleticPoint = 25  # 获得竞技点

    def initGuanQiaAward(self):
        """初始化关卡奖励"""
        partyInfo = s_partyInfo.datas.get(self.partyId)
        if not partyInfo:
            #             print 'ChooseMonsterError!'
            return {}
        self.partyExp = int(partyInfo['exp'] * (1 + self.partyExpAddPercent * 0.01))
        self.partyMoney = partyInfo['money']
        self.partySkillPoints = partyInfo['skillPoints']
        self.lootGroupId = partyInfo['lootGroupId']
        self.lootNumber = partyInfo['lootNumber']
        # if self.lootGroupId:
        #     lootGroup = dbDropout.DROPOUT_CONFIG.get(self.lootGroupId, [])
        #     if not lootGroup:
        #         log.err('dropGroup errer partyId:%d groupId:%d'%(self.partyId,self.lootGroupId))

    def DoRewordLoot(self):
        """处理关卡掉落"""
        if not self.lootGroupId or not self.lootNumber:
            return
        # self.lootList.extend(WorldManager().dropItem(self.lootGroupId, self.lootNumber))

    #         if not self.lootList:
    #             print u'掉落出错 总概率：%d 随机值：%d'%(amountOdds,odds)

    #         print u'关卡掉落 ：%s' % self.lootList

    def addSellItem(self, sellItem):
        """增加卖掉的物品信息"""
        self.lootSellList.append(sellItem)

    def addGetItem(self, getItem):
        """增加未卖掉的物品信息"""
        self.lootGetList.append(getItem)

    def initBattlefield(self):
        """初始化战场"""
        print('activeSideMembers: %s '%self.activeSideMembers.values())
        activeSideAllFightPower = 0  # 进攻方总战力
        passSideAllFightPower = 0  # 防御方总战斗力
        for member in self.activeSideMembers.values():
            if not member:
                continue
            activeSideAllFightPower += member.getFightPower()

        print('passiveSideMembers: %s ' % self.passiveSideMembers.values())
        for member in self.passiveSideMembers.values():
            if not member:
                continue
            passSideAllFightPower += member.getFightPower()

        if activeSideAllFightPower >= passSideAllFightPower:
            firstAtkSide = self.activeSideMembers
            secondAtkSide = self.passiveSideMembers
        else:
            firstAtkSide = self.passiveSideMembers
            secondAtkSide = self.activeSideMembers

        for index in range(6):
            position = index + 1
            member = firstAtkSide.get(position)
            if not member:
                continue
            self.fightOrder.append(member.getBaseID())
            passiveMember = secondAtkSide.get(position, None)
            if not passiveMember or passiveMember.getBaseID() in self.fightOrder:
                passiveMember = None
                for passMember in secondAtkSide.values():
                    if not passMember or passMember.getBaseID() in self.fightOrder:
                        continue
                    passiveMember = passMember
                    break
            if not passiveMember:
                continue
            self.fightOrder.append(passiveMember.getBaseID())

        for member in secondAtkSide.values():
            if not member:
                continue
            if member.getBaseID() not in self.fightOrder:
                self.fightOrder.append(member.getBaseID())

        for member in self.activeSideMembers.values():
            if not member:
                continue
            self.fighters[member.getBaseID()] = member.getFightData(1, isAthletics=self.isAthletics,
                                                                    isWorldBoss=self.isWorldBossFight)
            self.activeList.append(member.getBaseID())
            if self.fighters[member.getBaseID()]['expGodAdd'] > 0:
                self.partyExpAddPercent += self.fighters[member.getBaseID()]['expGodAdd']

        for passiveMember in self.passiveSideMembers.values():
            if not passiveMember:
                continue
            self.fighters[passiveMember.getBaseID()] = passiveMember.getFightData(2, isAthletics=self.isAthletics,
                                                                                  isWorldBoss=self.isWorldBossFight)
            self.passiveList.append(passiveMember.getBaseID())
            # 保存世界BOSSID
            if self.fighters[passiveMember.getBaseID()].get('worldBoss', 0) == 1 and not self.worldBoss:
                self.worldBoss = passiveMember.getBaseID()
                self.worldBossHp = self.fighters[passiveMember.getBaseID()]['chaCurrentHp']

    def findTarget(self, actorId, skillTarget):
        """寻找目标
        @param actorId: int 行动者的ID
        @param skillTarget: int 目标的类型
        """
        targetList = []  # 技能作用目标
        actor = self.fighters[actorId]
        actor_Camp = actor['chaDirection']  # 根据行动者的id得到行动者所在战场的阵营
        actor_Row = actor['fightRow']  # 获取行动者所在行

        ruleDict = {1: [1, 2, 3, 4, 5, 6], 2: [2, 1, 3, 5, 4, 6], 3: [3, 1, 2, 6, 5, 4]}  # 不同行的寻找对手规则

        skillTargetInfo = s_skillTarget.datas.get(skillTarget, {})
        if not skillTargetInfo:
            return targetList
        targetCamp = skillTargetInfo.get('targetCamp', -1)
        targetMainType = skillTargetInfo.get('mainType', 0)
        targetSubType = skillTargetInfo.get('subType', 0)
        targetNum = skillTargetInfo.get('targetNum', 0)
        # 查找目标集合
        if targetCamp == 0:
            targetList.append(actorId)
            # 返回集合ID
            return targetList
        elif targetCamp == 1:  # 目标为敌方
            if actor_Camp == 1:  # 行动者为攻击方
                sideMembers = self.passiveSideMembers
            else:  # 行动者为防御方
                sideMembers = self.activeSideMembers
        elif targetCamp == 2:  # 目标为己方
            if actor_Camp == 1:  # 行动者为攻击方
                sideMembers = self.activeSideMembers
            else:  # 行动者为防御方
                sideMembers = self.passiveSideMembers
        else:
            return targetList

        tempTargetList = []
        sortList = []
        # 计算有多少目标总数
        for position in ruleDict.get(actor_Row):
            member = sideMembers.get(position)
            if member and member.getBaseID() in self.fighters.keys() and self.fighters[member.getBaseID()][
                'chaCurrentHp'] > 0:
                sortList.append({'baseId': member.getBaseID(),
                                 'hp': int(round((float(self.fighters[member.getBaseID()]['chaCurrentHp']) /
                                                  self.fighters[member.getBaseID()]['chaMaxHp']) * 100)),
                                 'mp': int(round((float(self.fighters[member.getBaseID()]['chaCurrentMp']) /
                                                  self.fighters[member.getBaseID()]['chaMaxMp']) * 100))})
        sortListHpUp = sorted(sortList, key=operator.itemgetter('hp'))  # HP从小到大排序
        sortListHpDown = sorted(sortList, key=operator.itemgetter('hp'), reverse=True)  # HP从大到小排序
        sortListMpUp = sorted(sortList, key=operator.itemgetter('mp'))  # MP从小到大排序
        sortListMpDown = sorted(sortList, key=operator.itemgetter('mp'), reverse=True)  # MP从大到小排序

        if targetSubType == 1:  # 生命最高
            for target in sortListHpDown:
                tempTargetList.append(target.get('baseId'))
        elif targetSubType == 2:  # 生命最低
            for target in sortListHpUp:
                tempTargetList.append(target.get('baseId'))
        elif targetSubType == 3:  # 怒气最高
            for target in sortListMpDown:
                tempTargetList.append(target.get('baseId'))
        elif targetSubType == 4:  # 怒气最低
            for target in sortListMpUp:
                tempTargetList.append(target.get('baseId'))
        else:  # 默认
            for target in sortList:
                tempTargetList.append(target.get('baseId'))

        if not tempTargetList:
            return targetList

        # 确定目标
        if targetMainType == 2:  # 全体
            targetList.extend(tempTargetList)
        elif targetMainType == 1:  # 单体
            targetList.append(tempTargetList[0])
        elif targetMainType == 3:  # 随机
            if len(tempTargetList) <= targetNum:
                targetList.extend(tempTargetList)
            else:
                targetList.extend(random.sample(tempTargetList, targetNum))
        elif targetMainType == 4:  # 直线
            lineList = {1: [[1, 4], [2, 5], [3, 6]],
                        2: [[2, 5], [1, 4], [3, 6]],
                        3: [[3, 6], [1, 4], [2, 5]]}.get(actor_Row)
            targetTList = []
            for line in lineList:
                member1 = sideMembers.get(line[0], None)
                member2 = sideMembers.get(line[1], None)
                if not member1 and not member2:
                    continue
                if member1 and self.fighters[member1.getBaseID()]['chaCurrentHp'] > 0:
                    targetTList.append(member1.getBaseID())
                if member2 and self.fighters[member2.getBaseID()]['chaCurrentHp'] > 0:
                    targetTList.append(member2.getBaseID())
                if not targetTList:
                    continue
                if targetNum >= len(targetTList) or targetNum == 0 or len(targetTList) == 1:
                    targetList.extend(targetTList)
                else:
                    if targetSubType == 0:
                        targetList.append(targetTList[0])
                    else:
                        indexA = tempTargetList.index(targetTList[0])
                        indexB = tempTargetList.index(targetTList[1])
                        if indexA < indexB:
                            targetList.append(tempTargetList[indexA])
                        else:
                            targetList.append(tempTargetList[indexB])
                if targetList:
                    break
        elif targetMainType == 5 or targetMainType == 6:  # 前排 or 后排
            rowList = {5: {1: [[1, 2, 3], [4, 5, 6]],
                           2: [[2, 1, 3], [4, 5, 6]],
                           3: [[3, 1, 2], [4, 5, 6]]},
                       6: {1: [[4, 5, 6], [1, 2, 3]],
                           2: [[5, 4, 6], [1, 2, 3]],
                           3: [[6, 5, 4], [1, 2, 3]]}}.get(targetMainType).get(actor_Row)
            targetTList = []
            for row in rowList:
                member1 = sideMembers.get(row[0], None)
                member2 = sideMembers.get(row[1], None)
                member3 = sideMembers.get(row[2], None)
                if not member1 and not member2 and not member3:
                    continue
                if member1 and self.fighters[member1.getBaseID()]['chaCurrentHp'] > 0:
                    targetTList.append(member1.getBaseID())
                if member2 and self.fighters[member2.getBaseID()]['chaCurrentHp'] > 0:
                    targetTList.append(member2.getBaseID())
                if member3 and self.fighters[member3.getBaseID()]['chaCurrentHp'] > 0:
                    targetTList.append(member3.getBaseID())
                if not targetTList:
                    continue
                if targetNum >= len(targetTList) or targetNum == 0 or len(targetTList) == 1:
                    targetList.extend(targetTList)
                else:
                    if targetSubType == 0:
                        targetList.extend(targetTList[0:targetNum])
                    else:
                        targetIndexList = []
                        for targetId in targetTList:
                            targetIndexList.append(tempTargetList.index(targetId))
                        targetIndexList.sort()
                        targetList.extend(targetIndexList[0:targetNum])
                if targetList:
                    break
        elif targetMainType == 7:  # 固定数目
            if len(tempTargetList) <= targetNum:
                targetList.extend(tempTargetList)
            else:
                targetList.extend(tempTargetList[0:targetNum])
        # 返回集合ID
        return targetList

    def doFightDied(self, diedFighterId):
        """单位死亡"""
        if diedFighterId in self.activeList:
            del self.activeList[self.activeList.index(diedFighterId)]
        elif diedFighterId in self.passiveList:
            del self.passiveList[self.passiveList.index(diedFighterId)]

        self.battleStateMachine.clearAllBuff(diedFighterId)

    def DoFight(self):
        """战斗计算
        """
        while True:  # 如果一方的所有成员死亡，或者总回合数超过30回合，战斗结束
            print(u'activeList: %s' % self.activeList)
            print(u'passiveList: %s' % self.passiveList)
            if (not self.activeList) or (not self.passiveList) or self.now_round > self.MAX_ROUND:
                break
            self.now_round += 1
            print(u'第 Round%d 回合:' % self.now_round)
            self.RoundProcess()  # 每回合处理

        if self.activeList and self.now_round <= self.MAX_ROUND:
            self.battleResult = 1  # 胜利
        else:
            self.battleResult = 2  # 失败

        if self.worldBoss:
            self.worldBossReMindHp = self.fighters[self.worldBoss]['chaCurrentHp']

        print(u'battleResult: %s' % {1: u'胜利', 2: u'失败'}.get(self.battleResult))

        print(u'战斗数据:%s' % self.FightData)

    def RoundProcess(self):
        """回合处理"""
        # if self.fightOrder:
        #     print u'攻击序列:%s' % self.fightOrder
        for actor in self.fightOrder:
            if (not self.activeList) or (not self.passiveList) or self.now_round > self.MAX_ROUND:
                break
            if (actor not in self.activeList) and (actor not in self.passiveList):
                continue
            self.goFight(actor)

    def doBufferEffect(self, actorId, data):
        """处理buff效果
        @param actorId: int 行动者的ID
        """
        return self.battleStateMachine.executeBuffEffects(actorId, data)

    def goFight(self, actorId):
        """开始战斗计算
        @param actorId: int 行动者的ID
        """
        actor = self.battleStateMachine.getTargetAttrWithBuf(actorId)
        if self.fighters[actorId]['died'] == 1:
            return
        releaseIndex = self.fighters[actorId]['nextReleaseSkill']  # 角色释放技能的序号
        if self.fighters[actorId]['ActiveSkillList']:
            skillID = self.fighters[actorId]['ActiveSkillList'][releaseIndex]  # 角色要释放的战斗技能
        else:
            skillID = self.fighters[actorId]['ordSkill']
        self.doSkill(actor, skillID)

    def doSkillEffect(self, skillId, data, actor):
        """执行技能效果"""
        skillInfo = s_skillProperty.datas.get(skillId, {})
        if not skillInfo:
            return
        skillEffectId = skillInfo.get('skillEffect', 0)
        if skillEffectId == 0:
            return
        effectInfo = s_skillEffect.datas.get(skillEffectId, {})
        if not effectInfo:
            return
        data['mainTarget'].extend(list(self.findTarget(actor['chaId'], skillInfo.get('mainTargetType', 0))))
        self.addSkillTarget(data, actor, data['mainTarget'], effectInfo)
        if data['mainTarget'] and effectInfo.get('effectType', 0) == ConstantDefine.DEFINE_EFFECT_TYPE_HURT and (
                effectInfo.get('hurtType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_TYPE_REGAIN_SP or \
                effectInfo.get('hurtType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_TYPE_TREAT):
            data['subTarget'].extend(list(self.findTarget(actor['chaId'], skillInfo.get('subTargetType', 0))))
            self.addSkillTarget(data, actor, data['subTarget'])

        self.skillEffectCalculate(data, actor, data['mainTarget'], data['subTarget'], effectInfo)

    def addSkillTarget(self, data, actor, targetList, effectInfo=None):
        """增加技能释放目标"""
        if effectInfo is None:
            effectInfo = {}
        for targetId in targetList:
            enemy = self.fighters[targetId]
            if targetId not in data['enemyChaArr'].keys():
                if effectInfo:
                    data['enemyChaArr'][targetId] = {'enemyChaId': enemy['chaId'], 'enemyChaName': enemy['chaName'],
                                                     'enemychaLevel': enemy['chaLevel'],
                                                     'enemyBattleId': enemy['chaBattleId'], 'enemyBuffArr': [],
                                                     'enemyNewBuffArr': [], 'enemyMaxHp': enemy['chaMaxHp'],
                                                     'enemyChangeHp': 0, 'enemyCurrentHp': enemy['chaCurrentHp'],
                                                     'enemyMaxMp': enemy['chaMaxMp'], 'enemyChangeMp': 0,
                                                     'enemyCurrentMp': enemy['chaCurrentMp'], 'enemyCounterHit': 0,
                                                     'enemyDirection': enemy['chaDirection'],
                                                     'enemyBeHurt': enemy['canBeNotHurt'],
                                                     'enemyBeCri': {False: 0, True: 1}.get(
                                                         CalculateSkillCri(actor, effectInfo)),
                                                     'enemyDodge': {False: 0, True: 1}.get(
                                                         CalculateSkillDadog(enemy, effectInfo)),
                                                     'enemySkipAtk': 0, 'actorSkillChangeHp': 0,
                                                     'actorSkillChangeMp': 0, 'died': enemy['died'],
                                                     'armor': enemy['armor'],
                                                     'buffEffect': [], 'skillHurt': 0}
                else:
                    data['enemyChaArr'][targetId] = {'enemyChaId': enemy['chaId'], 'enemyChaName': enemy['chaName'],
                                                     'enemychaLevel': enemy['chaLevel'],
                                                     'enemyBattleId': enemy['chaBattleId'], 'enemyBuffArr': [],
                                                     'enemyNewBuffArr': [], 'enemyMaxHp': enemy['chaMaxHp'],
                                                     'enemyChangeHp': 0, 'enemyCurrentHp': enemy['chaCurrentHp'],
                                                     'enemyMaxMp': enemy['chaMaxMp'], 'enemyChangeMp': 0,
                                                     'enemyCurrentMp': enemy['chaCurrentMp'], 'enemyCounterHit': 0,
                                                     'enemyDirection': enemy['chaDirection'],
                                                     'enemyBeHurt': 0, 'enemyBeCri': 0, 'enemyDodge': 0,
                                                     'enemySkipAtk': 0, 'actorSkillChangeHp': 0,
                                                     'actorSkillChangeMp': 0,
                                                     'died': enemy['died'], 'armor': enemy['armor'], 'buffEffect': [],
                                                     'skillHurt': 0}

    def skillEffectCalculate(self, data, actor, mainTargetList, subTargetList, effectInfo):
        """计算技能效果"""
        if effectInfo.get('effectType', 0) == ConstantDefine.DEFINE_EFFECT_TYPE_HURT:  # 伤害
            self.skillEffectCalculateHurt(data, actor, mainTargetList, subTargetList, effectInfo)
        elif effectInfo.get('effectType', 0) == ConstantDefine.DEFINE_EFFECT_TYPE_PRODUCE_SP:  # 生成怒气
            self.skillEffectCalculateProduceMp(data, mainTargetList, effectInfo)
        elif effectInfo.get('effectType', 0) == ConstantDefine.DEFINE_EFFECT_TYPE_REODUCE_SP:  # 削减怒气
            self.skillEffectCalculateReoduceMp(data, mainTargetList, effectInfo)
        elif effectInfo.get('effectType', 0) == ConstantDefine.DEFINE_EFFECT_TYPE_TREAT:  # 治疗
            self.skillEffectCalculateTreatHp(data, mainTargetList, effectInfo)

    def skillEffectCalculateTreatHp(self, data, mainTargetList, effectInfo):
        """治疗"""
        for mainTarget in mainTargetList:
            data['enemyChaArr'][mainTarget]['enemyBeCri'] = 0
            if mainTarget not in self.fighters.keys() or self.fighters[mainTarget]['died'] == 1:
                continue
            produceHp = HpProduce(self.fighters[mainTarget], effectInfo, self.fighters[data['chaId']])
            self.recoverHp(data, mainTarget, produceHp)

    def skillEffectCalculateReoduceMp(self, data, mainTargetList, effectInfo):
        """削减怒气"""
        for mainTarget in mainTargetList:
            if mainTarget not in self.fighters.keys() or self.fighters[mainTarget]['died'] == 1:
                continue
            produceMp = MpProduce(self.fighters[mainTarget], effectInfo)
            self.deductMp(data, mainTarget, produceMp)

    def skillEffectCalculateProduceMp(self, data, mainTargetList, effectInfo):
        """生成怒气"""
        for mainTarget in mainTargetList:
            if mainTarget not in self.fighters.keys() or self.fighters[mainTarget]['died'] == 1:
                continue
            produceMp = MpProduce(self.fighters[mainTarget], effectInfo)
            self.recoverMp(data, mainTarget, produceMp)

    def skillEffectCalculateHurt(self, data, actor, mainTargetList, subTargetList, effectInfo):
        """计算效果伤害"""
        for mainTarget in mainTargetList:
            if mainTarget not in self.fighters.keys() or self.fighters[mainTarget]['died'] == 1:
                continue
            damage = DamageFormula(actor, self.fighters[mainTarget], data['enemyChaArr'][mainTarget]['enemyBeCri'],
                                   effectInfo)
            # 无敌
            if self.fighters[mainTarget]['canBeNotHurt'] == 1 or data['enemyChaArr'][mainTarget]['enemyDodge'] == 1:
                continue
            data['enemyChaArr'][mainTarget]['skillHurt'] += damage
            self.deductHp(data, mainTarget, damage)
            self.battleStateMachine.executeBuffEffectsByAtk(mainTarget, data, damage)
            self.hurtGodAssimilateHp(data, actor, damage)  # 神属性吸血
            if effectInfo.get('hurtType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_TYPE_NOMAL:  # 普通直接伤害
                continue
            elif effectInfo.get('hurtType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_TYPE_DRAINS:  # 吸血
                self.hurtAssimilateHp(data, actor, damage, effectInfo)
            elif effectInfo.get('hurtType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_TYPE_REGAIN_SP:  # 伤害回怒
                self.hurtRecoverMp(data, damage, effectInfo, subTargetList)
            elif effectInfo.get('hurtType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_TYPE_GET_SP:  # 伤害吸取怒气
                self.deductMp(data, mainTarget, self.hurtAssimilateMp(data, actor, damage, effectInfo))
            elif effectInfo.get('hurtType', 0) == ConstantDefine.DEFINE_EFFECT_HURT_TYPE_TREAT:  # 伤害治疗
                self.hurtTreatHp(data, damage, effectInfo, subTargetList)

    def hurtTreatHp(self, data, damage, effectInfo, subTargetList):
        """伤害治疗"""
        recoverHpValue = 0
        if effectInfo.get('hurtSubValueType', 0) == 0:
            return
        elif effectInfo.get('hurtSubValueType', 0) == ConstantDefine.DEFINE_EFFECT_SUB_HURT_VALUE_TYPE_PERCENT:  # 伤害百分比
            recoverHpValue += int(round(damage * effectInfo.get('hurtSubValue', 0)) * 0.01)
        elif effectInfo.get('hurtSubValueType', 0) == ConstantDefine.DEFINE_EFFECT_SUB_HURT_VALUE_TYPE_FIXED:  # 固定值
            recoverHpValue += effectInfo.get('hurtSubValue', 0)
        for targetId in subTargetList:
            self.recoverHp(data, targetId, recoverHpValue)

    def hurtAssimilateMp(self, data, actor, damage, effectInfo):
        """伤害吸取怒气"""
        assimilateMpValue = 0
        if effectInfo.get('hurtSubValueType', 0) == 0:
            return assimilateMpValue
        elif effectInfo.get('hurtSubValueType', 0) == ConstantDefine.DEFINE_EFFECT_SUB_HURT_VALUE_TYPE_PERCENT:  # 伤害百分比
            assimilateMpValue += int(round(damage * effectInfo.get('hurtSubValue', 0)) * 0.01)
        elif effectInfo.get('hurtSubValueType', 0) == ConstantDefine.DEFINE_EFFECT_SUB_HURT_VALUE_TYPE_FIXED:  # 固定值
            assimilateMpValue += effectInfo.get('hurtSubValue', 0)
        self.recoverMp(data, actor['chaId'], assimilateMpValue)
        return assimilateMpValue

    def hurtRecoverMp(self, data, damage, effectInfo, subTargetList):
        """伤害回复怒气"""
        recoverMpValue = 0
        if effectInfo.get('hurtSubValueType', 0) == 0:
            return
        elif effectInfo.get('hurtSubValueType', 0) == ConstantDefine.DEFINE_EFFECT_SUB_HURT_VALUE_TYPE_PERCENT:  # 伤害百分比
            recoverMpValue += int(round(damage * effectInfo.get('hurtSubValue', 0)) * 0.01)
        elif effectInfo.get('hurtSubValueType', 0) == ConstantDefine.DEFINE_EFFECT_SUB_HURT_VALUE_TYPE_FIXED:  # 固定值
            recoverMpValue += effectInfo.get('hurtSubValue', 0)
        for targetId in subTargetList:
            self.recoverMp(data, targetId, recoverMpValue)

    def godRecoverHp(self, data, actor):
        """神属性回复血"""
        recoverHp = int(
            round(self.fighters[actor['chaId']]['chaMaxHp'] * self.fighters[actor['chaId']]['recoverHpGodAdd']) * 0.01)
        self.recoverHp(data, actor['chaId'], recoverHp, True)

    def hurtGodAssimilateHp(self, data, actor, damage):
        """神属性吸血"""
        assimilateHpValue = int(round(damage * self.fighters[actor['chaId']]['absorbHpGodAdd']) * 0.01)
        self.recoverHp(data, actor['chaId'], assimilateHpValue)

    def hurtAssimilateHp(self, data, actor, damage, effectInfo):
        """吸取生命"""
        assimilateHpValue = 0
        if effectInfo.get('hurtSubValueType', 0) == 0:
            return
        elif effectInfo.get('hurtSubValueType', 0) == ConstantDefine.DEFINE_EFFECT_SUB_HURT_VALUE_TYPE_PERCENT:  # 伤害百分比
            assimilateHpValue += int(round(damage * effectInfo.get('hurtSubValue', 0)) * 0.01)
        elif effectInfo.get('hurtSubValueType', 0) == ConstantDefine.DEFINE_EFFECT_SUB_HURT_VALUE_TYPE_FIXED:  # 固定值
            assimilateHpValue += effectInfo.get('hurtSubValue', 0)
        self.recoverHp(data, actor['chaId'], assimilateHpValue, isSkillGet=True)

    def recoverHp(self, data, targetId, hpValue, isGodChange=False, isSkillGet=False):
        """恢复生命"""
        # 生命恢复削弱
        hpValue -= int(round(self.fighters[targetId]['deHpRecoverPercent'] * 0.01 * hpValue))
        hpValue -= self.fighters[targetId]['deHpRecover']
        self.fighters[targetId]['chaCurrentHp'] += hpValue
        if isGodChange:
            data['godHpChange'] += hpValue
        if isSkillGet:
            data['skillHurtGetHp'] += hpValue
        if self.fighters[targetId]['chaCurrentHp'] >= self.fighters[targetId]['chaMaxHp']:
            self.fighters[targetId]['chaCurrentHp'] = self.fighters[targetId]['chaMaxHp']
        if targetId in data['enemyChaArr'].keys():
            data['enemyChaArr'][targetId]['enemyCurrentHp'] = self.fighters[targetId]['chaCurrentHp']
            data['enemyChaArr'][targetId]['enemyChangeHp'] += hpValue
        if data['chaId'] == targetId:
            data['chaCurrentHp'] = self.fighters[targetId]['chaCurrentHp']
            data['chaChangeHp'] += hpValue

    def deductHp(self, data, targetId, hpValue):
        """扣除生命"""
        changeHp = hpValue
        # 优先扣除护甲
        if self.fighters[targetId]['armor'] > 0:
            self.fighters[targetId]['armor'] -= hpValue
            if self.fighters[targetId]['armor'] < 0:
                hpValue = abs(self.fighters[targetId]['armor'])
                self.fighters[targetId]['armor'] = 0
            else:
                hpValue = 0
        # 扣除血量
        self.fighters[targetId]['chaCurrentHp'] -= hpValue
        # 判断死亡
        if self.fighters[targetId]['chaCurrentHp'] <= 0:
            self.fighters[targetId]['chaCurrentHp'] = 0
            self.fighters[targetId]['died'] = 1
            self.doFightDied(targetId)

        if targetId in data['enemyChaArr'].keys():
            data['enemyChaArr'][targetId]['enemyChangeHp'] -= changeHp
            data['enemyChaArr'][targetId]['armor'] = self.fighters[targetId]['armor']
            data['enemyChaArr'][targetId]['enemyCurrentHp'] = self.fighters[targetId]['chaCurrentHp']
            data['enemyChaArr'][targetId]['died'] = self.fighters[targetId]['died']
        if data['chaId'] == targetId:
            data['armor'] = self.fighters[targetId]['armor']
            data['chaCurrentHp'] = self.fighters[targetId]['chaCurrentHp']
            data['chaChangeHp'] -= changeHp
            data['died'] = self.fighters[targetId]['died']

    def recoverMp(self, data, targetId, mpValue):
        """恢复怒气"""
        self.fighters[targetId]['chaCurrentMp'] += mpValue
        if self.fighters[targetId]['chaCurrentMp'] > self.fighters[targetId]['chaMaxMp']:
            self.fighters[targetId]['chaCurrentMp'] = self.fighters[targetId]['chaMaxMp']
        if targetId in data['enemyChaArr'].keys():
            data['enemyChaArr'][targetId]['enemyCurrentMp'] = self.fighters[targetId]['chaCurrentMp']
            data['enemyChaArr'][targetId]['enemyChangeMp'] += mpValue
        if data['chaId'] == targetId:
            data['chaCurrentMp'] = self.fighters[targetId]['chaCurrentMp']
            data['chaChangeMp'] += mpValue
        # print u'角色最大怒气值:%d,角色怒气值:%d'%(self.fighters[targetId]['chaMaxMp'],self.fighters[targetId]['chaCurrentMp'])

    def deductMp(self, data, targetId, mpValue):
        """扣除怒气"""
        self.fighters[targetId]['chaCurrentMp'] -= mpValue
        if self.fighters[targetId]['chaCurrentMp'] < 0:
            self.fighters[targetId]['chaCurrentMp'] = 0
        if targetId in data['enemyChaArr'].keys():
            data['enemyChaArr'][targetId]['enemyCurrentMp'] = self.fighters[targetId]['chaCurrentMp']
            data['enemyChaArr'][targetId]['enemyChangeMp'] -= mpValue
        if data['chaId'] == targetId:
            data['chaCurrentMp'] = self.fighters[targetId]['chaCurrentMp']
            data['chaChangeMp'] -= mpValue

    def doSkill(self, actor, skillId):
        """进行技能攻击"""
        # print 'doSkill: %s skillId:%d'%(actor['chaId'],skillId)
        data = {}
        data['now_round'] = self.now_round  # 当前回合
        data['chaId'] = actor['chaId']  # 角色的Id
        data['type'] = 1  # 攻击类型 1：主动 2：BUFF
        data['chaName'] = actor['chaName']  # 攻击方得名称
        data['chaLevel'] = actor['chaLevel']  # 攻击方等级
        data['chaBattleId'] = actor['chaBattleId']  # 角色战斗位置ID
        data['skill'] = skillId
        data['chaProfessionType'] = actor['chaProfessionType']  # 角色的职业
        data['isDeathOfCounterHit'] = 0  # 攻击方是否被反击致死 0:否，1：是
        data['chaBuffArr'] = []  # 角色身上的buff
        data['chaMaxHp'] = actor['chaMaxHp']  # 角色总血量
        data['chaChangeHp'] = 0  # ±20 正负HP，可能有加血技能
        data['chaChangeMp'] = 0  # ±20 正负MP，可能有加蓝技能
        data['chaExpendHp'] = 0  # 角色技能消耗的血量
        data['chaCurrentHp'] = actor['chaCurrentHp']  # 角色的当前血量
        data['chaMaxMp'] = actor['chaMaxMp']  # 角色总魔法值
        data['chaCurrentMp'] = actor['chaCurrentMp']  # 角色的当前血量
        data['chaExpendMp'] = 0  # 角色技能消耗的魔法
        data['isCriticalBlow'] = False  # 是否暴击
        data['chaDirection'] = actor['chaDirection']  # 玩家朝向右，朝向右。2--玩家朝向左
        data['enemyChaArr'] = {}  # 所有受攻击者的信息
        data['buffEffect'] = []
        data['mainTarget'] = []
        data['subTarget'] = []
        data['died'] = 0  # 死亡
        data['armor'] = actor['armor']  # 护甲
        data['skipAtk'] = 0  # 是否跳过了本轮攻击，被晕眩
        data['godHpChange'] = 0  # 神属性血量变化
        data['skillHurtGetHp'] = 0  # 技能吸取血量变化

        # 神属性回血
        self.godRecoverHp(data, actor)
        # 处理BUFF
        if not self.doBufferEffect(actor['chaId'], data):
            if self.fighters[actor['chaId']]['ActiveSkillList']:
                self.fighters[actor['chaId']]['nextReleaseSkill'] += 1  # 下次释放技能的序号指向下一个技能
                if self.fighters[actor['chaId']]['nextReleaseSkill'] >= len(actor['ActiveSkillList']):
                    self.fighters[actor['chaId']]['nextReleaseSkill'] = 0
        # 减少BUFF回合数
        self.battleStateMachine.cutBuffTraceCD(actor['chaId'])

        if self.fighters[actor['chaId']]['died'] == 1:
            self.FightData.append(data)
            return

        if data['skipAtk'] == 1:
            # 检查BUFFCD
            self.battleStateMachine.checkBuffCD(actor['chaId'])
            data['chaBuffArr'] = self.battleStateMachine.getTargetBuffIDList(actor['chaId'])
            self.FightData.append(data)
            return
        # 容错处理
        if skillId not in s_skillProperty.datas.keys():
            log.err("skillId %d not exist" % skillId)
            return
        skillExpendMp = s_skillProperty.datas[skillId]['skillExpendSp']  # 技能魔法消耗
        # 检测魔法消耗
        if self.fighters[actor['chaId']]['chaCurrentMp'] < skillExpendMp:
            skillId = self.fighters[actor['chaId']]['ordSkill']
            data['skill'] = skillId
            skillExpendMp = s_skillProperty.datas[skillId]['skillExpendSp']  # 技能魔法消耗

        # 产生怒气
        self.recoverMp(data, actor['chaId'], s_skillProperty.datas[skillId]['skillProduceSp'])

        # 执行技能效果
        self.doSkillEffect(skillId, data, actor)
        # 执行技能BUFF附加
        self.doAddSkillBuff(skillId, data, actor)

        # ----------------------------------------------------------------
        if data['enemyChaArr']:
            if self.fighters[actor['chaId']]['ActiveSkillList']:
                self.fighters[actor['chaId']]['nextReleaseSkill'] += 1  # 下次释放技能的序号指向下一个技能
                if self.fighters[actor['chaId']]['nextReleaseSkill'] >= len(actor['ActiveSkillList']):
                    self.fighters[actor['chaId']]['nextReleaseSkill'] = 0
            for targetId, target in data['enemyChaArr'].items():
                target['enemyBuffArr'] = self.battleStateMachine.getTargetBuffIDList(targetId)
        # 扣除怒气
        self.deductMp(data, actor['chaId'], skillExpendMp)
        data['chaExpendMp'] += skillExpendMp
        # 检查BUFFCD
        self.battleStateMachine.checkBuffCD(actor['chaId'])
        data['chaBuffArr'] = self.battleStateMachine.getTargetBuffIDList(actor['chaId'])
        # if data['enemyChaArr']:
        #     for enemyInfo in data['enemyChaArr'].values():
        #         print u'%s 对 %s 造成了 %d 伤害' % (data['chaName'].encode('utf-8'), enemyInfo['enemyChaName'].encode('utf-8'), abs(enemyInfo['enemyChangeHp']))
        #         if enemyInfo['died']:
        #             print u'%s 死亡了' % enemyInfo['enemyChaName']
        self.FightData.append(data)

    def addBuff(self, data, targetId, skillBuffId, actorId, skillHurtValue=0):
        """附加BUFF"""
        randomValue = random.randint(0, 10000)
        skillAddOdds = s_skillBuff.datas.get(skillBuffId, {}).get('addOdds', 0)
        if randomValue <= skillAddOdds:
            needExecuteEffects = True
            if self.battleStateMachine.checkIsExistBuff(targetId, skillBuffId):
                needExecuteEffects = False
            self.battleStateMachine.addNewBuff(targetId, skillBuffId, actorId, skillHurtValue)
            if needExecuteEffects:
                self.battleStateMachine.executeBuffEffectsNew(targetId, data, skillBuffId)

    def doAddSkillBuff(self, skillId, data, actor):
        """处理技能附加BUFF"""
        skillBuffSelf = s_skillProperty.datas[skillId]['skillBuffSelf']
        skillBuffMainTarget = s_skillProperty.datas[skillId]['skillBuffMainTarget']
        skillSpecialBuff1 = s_skillProperty.datas[skillId]['skillSpecialBuff1']
        skillSpecialBuff1TargetType = s_skillProperty.datas[skillId]['skillSpecialBuff1TargetType']
        skillSpecialBuff2 = s_skillProperty.datas[skillId]['skillSpecialBuff2']
        skillSpecialBuff2TargetType = s_skillProperty.datas[skillId]['skillSpecialBuff2TargetType']
        if skillBuffSelf:
            self.addBuff(data, actor['chaId'], skillBuffSelf, actor['chaId'])
        if skillBuffMainTarget:
            for target in data['mainTarget']:
                if target not in data['enemyChaArr'].keys() or data['enemyChaArr'][target]['enemyDodge']:
                    continue
                self.addBuff(data, target, skillBuffMainTarget, data['chaId'], data['enemyChaArr'][target]['skillHurt'])
        if skillSpecialBuff1 and skillSpecialBuff1TargetType:
            buffTargetList = self.findTarget(actor['chaId'], skillSpecialBuff1TargetType)
            if buffTargetList:
                self.addSkillTarget(data, actor, buffTargetList)
            for target in buffTargetList:
                if target not in data['enemyChaArr'].keys() or data['enemyChaArr'][target]['enemyDodge']:
                    continue
                self.addBuff(data, target, skillSpecialBuff1, data['chaId'], data['enemyChaArr'][target]['skillHurt'])
        if skillSpecialBuff2 and skillSpecialBuff2TargetType:
            buffTargetList = self.findTarget(actor['chaId'], skillSpecialBuff2TargetType)
            if buffTargetList:
                self.addSkillTarget(data, actor, buffTargetList)
            for target in buffTargetList:
                if target not in data['enemyChaArr'].keys() or data['enemyChaArr'][target]['enemyDodge']:
                    continue
                self.addBuff(data, target, skillSpecialBuff2, data['chaId'], data['enemyChaArr'][target]['skillHurt'])

    def formatInitFightData(self):
        """初始化战斗数据"""
        DEBUG_MSG("***********formatInitFightData %s", self.guanQia)
        msgFightResult = self._msgFightResult
        msgFightResult.Result = 1
        msgFightResult.GuanQia = self.guanQia
        fightRoleInfos = msgFightResult.FightRoleInfo  # 战斗方阵信息数组
        for roler in self.fighters.values():
            rolerInfo = MsgFightResult.StructFightRoleInitInfo()
            rolerInfo.RoleId = roler['figureType']  # 角色形象类型
            rolerInfo.RoleName = roler['chaName']  # 昵称
            rolerInfo.RoleType = roler['characterType']  # 角色类型 1:玩家角色 2:怪物 3:宠物
            rolerInfo.Horde = roler['chaDirection']  # 角色阵营 1:进攻 2:防守
            rolerInfo.Position = roler['chaBattleId']  # 方阵位置
            fightRoleInfos.append(rolerInfo)

            if self.isWorldBossFight:
                rolerInfo.Hp = self.worldBossHp  # 初始化世界BOSS血量
            else:
                rolerInfo.Hp = roler['chaCurrentHp']  # 当前血量 初始化所以是最大值

            rolerInfo.Mp = roler['chaCurrentMp']  # 当前魔法
            # print u'昵称:%s,怒气:%d'%(rolerInfo.RoleName,rolerInfo.Mp)
            rolerInfo.MaxHp = roler['chaMaxHp']  # 最大血量
            rolerInfo.MaxMp = roler['chaMaxMp']  # 最大魔法
            rolerInfo.Level = roler['chaLevel']  # 等级

    def formatFightData(self, fightType, fightBossTimes=0, rivalTimes=0):
        """格式化战斗的信息
        """
        msgFightResult = self._msgFightResult  # 战斗结果对象
        # msgFightResult.Reset()
        msgFightResult.FightBossTimes = fightBossTimes
        msgFightResult.AthleticTimes = rivalTimes
        msgFightResult.FightType = fightType
        fightRounds = msgFightResult.FightRoundGroup
        roundNum = 0

        fightRound = None
        for fightInfo in self.FightData:
            if roundNum != fightInfo['now_round']:
                fightRound = MsgFightResult.StructRoundInfo()
                roundNum = fightInfo['now_round']
                fightRound.RoundNumber = roundNum
                fightRounds.append(fightRound)
                # fightSetup = fightRound.FightSetupGroup.add()
            if not fightRound:
                break
            fightSetup = MsgFightResult.StructFightInfo()

            fightSetup.UserInfo.RoleId = fightInfo['chaId']
            fightSetup.UserInfo.RoleName = fightInfo['chaName']
            fightSetup.UserInfo.Horde = fightInfo['chaDirection']
            fightSetup.UserInfo.Position = fightInfo['chaBattleId']
            fightSetup.UserInfo.RemainHp = fightInfo['chaCurrentHp']
            fightSetup.UserInfo.RemainMp = fightInfo['chaCurrentMp']
            fightSetup.UserInfo.SkillId = fightInfo['skill']
            fightSetup.UserInfo.Profession = fightInfo['chaProfessionType']
            fightSetup.UserInfo.HpChange = fightInfo['chaChangeHp']
            fightSetup.UserInfo.MpChange = fightInfo['chaChangeMp']
            fightSetup.UserInfo.IsSkipFight = fightInfo['skipAtk']
            fightSetup.UserInfo.Armor = fightInfo['armor']
            fightSetup.UserInfo.GodHpChange = fightInfo['godHpChange']
            fightSetup.UserInfo.SkillGetHpChange = fightInfo['skillHurtGetHp']
            for buffId in fightInfo['chaBuffArr']:
                fightSetup.UserInfo.BuffList.append(buffId)
            for tiggerBuff in fightInfo['buffEffect']:
                tBuff = MsgFightResult.StructTiggerBuff()
                tBuff.BUFFId = tiggerBuff['BUFFId']
                tBuff.EffectType = tiggerBuff['EffectType']
                tBuff.EffectSubType = tiggerBuff['EffectSubType']
                tBuff.EffectValue = tiggerBuff['EffectValue']
                fightSetup.UserInfo.TiggerBuff.append(tBuff)

            for enemyInfo in fightInfo['enemyChaArr'].values():
                enemyRolerInfo = MsgFightResult.StructBattlefieldUserInfo()
                enemyRolerInfo.RoleId = enemyInfo['enemyChaId']
                enemyRolerInfo.RoleName = enemyInfo['enemyChaName']
                enemyRolerInfo.Horde = enemyInfo['enemyDirection']
                enemyRolerInfo.Position = enemyInfo['enemyBattleId']
                enemyRolerInfo.Hit = {0: 1, 1: 2}.get(enemyInfo['enemyDodge'])
                enemyRolerInfo.HpChange = enemyInfo['enemyChangeHp']
                enemyRolerInfo.MpChange = enemyInfo['enemyChangeMp']
                enemyRolerInfo.RemainHp = enemyInfo['enemyCurrentHp']
                enemyRolerInfo.RemainMp = enemyInfo['enemyCurrentMp']
                enemyRolerInfo.ImmuneHurt = {0: 1, 1: 2}.get(enemyInfo['enemyBeHurt'])
                enemyRolerInfo.IsBeCri = {0: 1, 1: 2}.get(enemyInfo['enemyBeCri'])
                enemyRolerInfo.Armor = enemyInfo['armor']
                # for buffId in enemyInfo['enemyNewBuffArr']:enemyRolerInfo.NewBuffList.append(buffId)
                for buffId in enemyInfo['enemyBuffArr']:
                    enemyRolerInfo.BuffList.append(buffId)
                fightSetup.EffectGroup.append(enemyRolerInfo)
                # enemyRolerInfo.ActorSkillChangeHp = enemyInfo['actorSkillChangeHp']
                # enemyRolerInfo.ActorSkillChangeMp = enemyInfo['actorSkillChangeMp']
                for tiggerBuff in enemyInfo['buffEffect']:
                    tBuff = MsgFightResult.StructTiggerBuff()
                    tBuff.BUFFId = tiggerBuff['BUFFId']
                    tBuff.EffectType = tiggerBuff['EffectType']
                    tBuff.EffectSubType = tiggerBuff['EffectSubType']
                    tBuff.EffectValue = tiggerBuff['EffectValue']
                    fightSetup.UserInfo.TiggerBuff.append(tBuff)
            fightRound.FightSetupGroup.append(fightSetup)

        msgFightResult.FResult = self.battleResult
        if self.battleResult == 1:
            #             if not self.isAthletics:
            msgFightResult.Exp = self.partyExp
            msgFightResult.Coin = self.partyMoney
            msgFightResult.SkillPoints = self.partySkillPoints
            msgFightResult.AthleticPoint = self.athleticPoint
            msgFightResult.TowerCoin = self.fightTowerCoin
            msgFightResult.Gold = self.fightTowerGold
            for item in self.lootGetList:  # 添加未售卖的物品
                lootItem = MsgFightResult.StructLootInfo()
                lootItem.ItemId = item['itemId']
                lootItem.ItemCount = item['itemNum']
                lootItem.ItemQuality = item['ItemQuality']
                msgFightResult.LootInfo.append(lootItem)
            for sellItem in self.lootSellList:
                lootItem = MsgFightResult.StructLootInfo()
                lootItem.ItemId = sellItem['itemId']
                lootItem.ItemCount = sellItem['itemNum']
                lootItem.Coin = sellItem['Coin']
                lootItem.ItemQuality = sellItem['ItemQuality']
                msgFightResult.LootInfo.append(lootItem)
            #             else:
        #                 msgFightResult.Coin = self.partyMoney
        #                 msgFightResult.AthleticPoint = self.athleticPoint
        else:
            if self.isAthletics:
                msgFightResult.Coin = self.partyMoney / 2
                msgFightResult.AthleticPoint = self.athleticPoint / 2
            else:
                msgFightResult.Coin = self.partyMoney

        for skillAddProficiency in self.skillProficiencyList:
            proficiencyInfo = MsgFightResult.StructSkillProficiency()
            proficiencyInfo.SkillId = skillAddProficiency['skillId']
            proficiencyInfo.AddProficiency = skillAddProficiency[
                'AddProficiency']
            proficiencyInfo.OldLevel = skillAddProficiency['oldLevel']
            proficiencyInfo.NewLevel = skillAddProficiency['newLevel']
            msgFightResult.SkillProficiency.append(proficiencyInfo)
        # print u'发送信息: 长度 %d' % len(data)
        return msgFightResult.toDict()
